// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-23

package info

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib"
)

// Logic
// 加载会员详情.
type Logic struct {
	admin  *models.ArcadeAdmins
	arcade *models.Arcades

	member *models.ArcadeMember
	user   *models.Users

	request  *Request
	response *Response
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

// Before
// 前置校验.
func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Query(i, o.request); err == nil {
		o.arcade, o.admin = lib.Arcade.GetMaster().GetArcade(i)
	}
	return
}

// Run
// 执行逻辑.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err error
		res = result.New()
	)
	if err = o.RunMember(ctx); err == nil {
		err = o.RunUser(ctx)
	}
	if err != nil {
		return res.WithError(err)
	}
	return res.With(o.response.With(o.member).WithUser(o.user))
}

func (o *Logic) RunMember(ctx context.Context) (err error) {
	var has bool
	if o.member, has, err = services.NewArcadeMemberService().Dao.GetById(ctx, o.request.Id); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}
	if !has || o.member.ArcadeId != o.arcade.Id {
		err = errs.ErrArcadeMemberNotFound
	}
	return
}

func (o *Logic) RunUser(ctx context.Context) (err error) {
	var has bool
	if o.user, has, err = services.NewUsersService().Dao.GetById(ctx, o.member.UserId); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}
	if !has {
		err = errs.ErrUserNotFound
	}
	return
}
